package com.zly.app.service;

import com.zly.app.dao.BackendUserDao;
import com.zly.app.dao.DevUserDao;
import com.zly.app.dto.LoginDto;
import com.zly.app.entity.BackendUser;
import com.zly.app.entity.DevUser;
import com.zly.app.util.SessionUtil;
import com.zly.app.util.SysConStatus;
import com.zly.app.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class LoginService {

    @Autowired
    DevUserDao devUserDao;
    @Autowired
    BackendUserDao backendUserDao;

    public LoginVo login(LoginDto loginDto) {
        LoginVo vo = new LoginVo();
       if (loginDto.getUserType().equals(SysConStatus.UserTypeInt.admin)){
           BackendUser backendUser = new BackendUser();
           backendUser.setUsercode(loginDto.getAccount());
           backendUser.setUserpassword(loginDto.getPassword());
           List<BackendUser> list = backendUserDao.queryAll(backendUser);
           if (list == null || list.size() == 0){
               throw new RuntimeException("密码或账号不正确");
           }
           vo.setUser(list.get(0));
           vo.setAccount(list.get(0).getUsercode());
           vo.setUserType(SysConStatus.UserTypeStr.admin);
           StringBuffer str = new StringBuffer();
           String uuid = UUID.randomUUID().toString().replace("-", "");
           str.append(uuid).append("-");
           str.append(list.get(0).getUsercode()).append("-");
           str.append(list.get(0).getId()).append("-");
           str.append("admin-");
           str.append(System.currentTimeMillis());
           SessionUtil.getToKen(str.toString(),list.get(0));
           vo.setToKen(str.toString());
           return vo;
       }else  if (loginDto.getUserType().equals(SysConStatus.UserTypeInt.dev)){
           DevUser devUser = new DevUser();
           devUser.setDevcode(loginDto.getAccount());
           devUser.setDevpassword(loginDto.getPassword());
           List<DevUser> list = devUserDao.queryAll(devUser);
           if (list == null || list.size() == 0){
               throw new RuntimeException("密码或账号不正确");
           }
           vo.setUser(list.get(0));
           vo.setAccount(list.get(0).getDevcode());
           vo.setUserType(SysConStatus.UserTypeStr.dev);
           StringBuffer str = new StringBuffer();
           String uuid = UUID.randomUUID().toString().replace("-", "");
           str.append(uuid).append("-");
           str.append(list.get(0).getDevcode()).append("-");
           str.append(list.get(0).getId()).append("-");
           str.append("dev-");
           str.append(System.currentTimeMillis());
           SessionUtil.getToKen(str.toString(),list.get(0));
           vo.setToKen(str.toString());
           return vo;
       }else{
           throw new RuntimeException("不存在的用户类型");
       }
    }
}
